package com.changy.ai_tutor_for_dm.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.changy.ai_tutor_for_dm.tools.JwtUtils;
import com.changy.ai_tutor_for_dm.context.UserContext;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 允许 /login 路径通过
        if (request.getRequestURI().equals("/login")) {
            return true;
        }
        log.info("JWT token interceptor preHandle");
        
        // 从请求头中获取 token
        String token = request.getHeader("JWTtoken");
        
        // 检查 token 是否存在
        if (token == null || token.isEmpty()) {
            // 将状态码设置为 401 Unauthorized
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("JWT token is missing");
            return false;
        }
        
        // 验证 JWT token 的有效性
        if (!isValidJwtToken(token)) {
            // 将状态码设置为 401 Unauthorized
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("JWT token is invalid");
            return false;
        }
        
        // token 有效，放行请求
        return true;
    }

    /**
     * 请求处理完成后执行
     * 清理threadlocal变量
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception ex) {
        UserContext.clearHolder(); // 清理 ThreadLocal
    }
    
    /**
     * 验证 JWT token 的有效性
     * @param token JWT token
     * @return token 是否有效
     */
    private boolean isValidJwtToken(String token) {
        // 这里实现具体的 JWT 验证逻辑
        try {
            // 解析 JWT token
            JwtUtils.parseJWT(token);

            // 将cardId保存到threadlocal变量中
            UserContext.setCardId(JwtUtils.parseJWT(token).get("cardId", String.class));

            return true; // 简化示例，实际需要实现验证逻辑
        } catch (Exception e) {
            log.warn("JWT token validation failed: {}", e.getMessage());

            return false;
        }
    }
}
